﻿using System;
using System.Threading.Tasks;
using Jinjia.Approve.Common.Enum;
using Jinjia.Approve.IService.JJFlow;
using Jinjia.Approve.Model.VM.JJFlow;
using JinJia.Core.Base.Exceptions;

namespace Jinjia.Approve.Service.JJFlow.Action
{
    public class JJFlowActionGoTo
    {
        protected readonly IJJFlowInstanceService _jjFlowInstanceService;
        protected readonly IJJFlowTrackService _jjFlowTrackService;

        public JJFlowActionGoTo(IJJFlowInstanceService jjFlowInstanceService, IJJFlowTrackService jjFlowTrackService)
        {
            _jjFlowInstanceService = jjFlowInstanceService;
            _jjFlowTrackService = jjFlowTrackService;
        }

        public virtual async Task<JjFlowInstanceVM> CheckAndGetFlowInstanceById(int instance_id)
        {
            //找到template
            var instance = await _jjFlowInstanceService.GetById(instance_id);
            if (instance == null)
            {
                throw new BusinessException("申请记录不存在！");
            }

            return instance;
        }

        public virtual void AssertHasNextNode(Node current_node)
        {
            if (current_node.node_type == (int)EnumDb.JJFlowNodeTypeEnum.EndNode)
            {
                throw new BusinessException("此流程已结束！");
            }
        }

        public virtual void AssertApprover(int user_id, int node_id, int template_id, int instance_id)
        {
            if (!_jjFlowInstanceService.CheckNodeUser(node_id, template_id, user_id, instance_id).Result)
            {
                throw new BusinessException("无审批权限！");
            }
        }

        public virtual void AssertExistTrack(int user_id, int node_id, int instance_id)
        {
            var result = _jjFlowInstanceService.CheckNodeTrack(node_id, user_id, instance_id).Result;
            if (result)
            {
                throw new BusinessException("请勿重复操作！");
            }
        }

        public virtual async Task RecordTrackInfo(Node next_node, int instance_id, int operate_user_id, int op_type, int user_id, string remark = "", int is_auto = 0)
        {
            await _jjFlowTrackService.RecordTrackInfo(next_node, instance_id, operate_user_id, op_type, user_id, remark, is_auto);
        }
    }
}